//react
import React, { Component, Fragment } from 'react';
import ReactDOM from 'react-dom';
//connect
import { connect } from 'dva';
//路由
import { routerRedux, Link } from 'dva/router';
//面包屑和title
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
//组件
import { Card, Button, Input, Select, Form, Row, Col, DatePicker, Divider,
  Popconfirm, message, Popover, Table, Badge, InputNumber } from 'antd';
//时间moment
import moment from 'moment';

//权限
import { checks } from '@/utils/authority';

import styles from './News.less';

//常量
const FormItem = Form.Item;
//详情路由
const infoPath = '/newsInfo';
const addPath = '/newsAdd';
//清楚model数据 方法
const clear = 'news/clear';
//存数据
const save = 'news/save';

//日常工作-列表
const list = 'news/fetch';
//删除
const del = 'news/remove';


//权限
//详情权限
const checksInfo = '/admin/news/detail';
//删除权限
const checksDel = '/admin/news/delete';
//修改权限
const checksUpdate = '/admin/news/update';
//添加权限
const checksAdd = '/admin/news/add';

@connect(state => ({
  news: state.news,
}))
@Form.create()
export default class News extends Component {
  //数据初始化
  state = {
    type: 0, //类型
    pageSize: 10, //页数
    showLoadMore: true,
    loadingMore: false,
    columns: [
      {
        title: '序号',
        dataIndex: 'index',
        width: '60px',
      },
      {
        key: 'title',
        title: '标题',
        dataIndex: 'title',
        render:(text,record)=>{
          if(checks(checksInfo)){
            return (
              <Link key="class" to={{pathname: infoPath, search: '?id=' + record.id}}>{text}</Link>
            )
          }else{
            return (
              <div>{text}</div>
            )
          }

        }
      },
      {
        title: '封面',
        dataIndex: 'cover',
        render: (text) =><div style={{backgroundImage:`url(${text})`}} className={styles.news_cover}></div>
      },
      {
        title: '类型',
        dataIndex: 'type',
        render: (text) =><div>{text}</div>
      },
      {
        title: '创建时间',
        dataIndex: 'gmtCreate',
        render: (text) =><div>{moment(text).format('YYYY-MM-DD')}</div>
      },
      {
        title: '操作',
        key: 'do',
        fixed: 'right',
        width: 105,
        render: (record) => {
          let btns = [];
          if (checks(checksUpdate)){
            btns.push(
              <Link key="link" to={{pathname: addPath, search: '?id=' + record.id}}>编辑</Link>
            )
          }
          if(checks(checksDel)&&checks(checksUpdate)){
            btns.push(
              <Divider key="line" type="vertical" />
            );
          }
          if (checks(checksDel)){
            btns.push(
              <Popconfirm title="你确定要删除吗?" onConfirm={() => this.handleDelete(record.id)} onCancel={this.cancel}>
                <a href="#">删除</a>
              </Popconfirm>
            )

          }
          return(
            <div key="item">
              <Fragment>
                {btns}
              </Fragment>
            </div>
          )
        }
      }
    ],
    scrollX: 1000,
    visible: false,
    auditVisible: false,
    showReason: false,
    id: 0,
  };
  //初始化加载页面
  componentDidMount() {
    const { pageSize } = this.state;
    const { dispatch } = this.props;
    dispatch({
      type: "news/clear"
    });
    var pathname = this.props.location.pathname;
    var type = 0;
    dispatch({
      type: 'news/fetch',
      payload: {
        pageSize: pageSize,
        type: type
      }
    });
    dispatch({
      type: 'news/save',
      payload:{
        pageSize: pageSize,
        type: type
      }
    });
    this.setState({
      pageSize: pageSize,
      type: type
    })
  }

  //重置
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      pageSize: 10
    });
    dispatch({
      type: 'news/save',
      payload: {title: "", pageSize: 10},
    });
    dispatch({
      type: 'news/fetch',
      payload: {pageSize: 10, type: this.state.type}
    });
  };
  //搜索
  handleSearch = (e) => {
    e.preventDefault();
    const { dispatch, news } = this.props;
    const { title } = news;
    this.setState({
      pageSize: 10
    });
    dispatch({
      type: "news/fetch",
      payload: {title: title, pageSize: 10, type: this.state.type}
    })
  };
  //inputOnChange
  inputChange(e){
    var key = e.target.name;
    var value = e.target.value;
    var t = {};
    t[key] = value;
    const { dispatch } = this.props;
    dispatch({
      type: "news/save",
      payload: t
    })
  }
  //搜索框
  renderSimpleForm() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form layout="inline">
        <Row md={8} lg={24} xl={48}>
          <Col md={8} sm={24}>
            <FormItem label="名称">
              {getFieldDecorator('title')(
                <Input name="title" onChange={this.inputChange.bind(this)} placeholder="请输入名称" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button style={{ marginLeft: 8 }} type="primary" onClick={this.handleSearch.bind(this)}>查询</Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset.bind(this)}>重置</Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }
  renderForm() {
    return this.renderSimpleForm();
  }
  //删除
  handleDelete(id) {
    const { dispatch } = this.props;
    dispatch({
      type: del,
      payload: {id: id}
    });
  }
  //取消删除
  cancel(){
    message.error('您取消了删除!');
  }

  /**
   * table列表上方法 ******* 开始 **********
   * */
  //table变化
  handleTableChange(pagination, filters, sorter){
    const { dispatch } = this.props;
    let dic = {};
    if (filters.state){
      dic["state"] = filters.state[0] ? filters.state[0]: '0';
    }
    if (filters.status){
      dic["status"] = filters.status[0] ? filters.status[0]: '0';
    }
    if (filters.type){
      dic["type"] = filters.type[0] ? filters.type[0]: '0';
    }
    dispatch({
      type: save,
      payload: dic
    });
    this.networkRequest();
  }
  //table分页
  onShowSizeChange(page, pageSize){
    if (!page || !pageSize){
      return;
    }
    this.changePage(page, pageSize);
  }
  onPageChange(page, pageSize){
    if (!page || !pageSize){
      return;
    }
    this.changePage(page, pageSize);
  }
  changePage(page, pageSize){
    const { dispatch } = this.props;
    dispatch({
      type: save,
      payload: {
        page: page,
        pageSize: pageSize,
      }
    });
    this.networkRequest();
  }

  //组件
  render() {
    //数据
    const { news: { dataList, page, pageSize, total, sort, loading } } = this.props;

    //返回组件
    var title = "新闻";

    /**
     * table配置 ********** 开始 ****************
     * data: 数据
     * pagination: 分页
     * */
      //数据 添加序号
    var data = [];
    if (dataList){
      for (let i = 0; i < dataList.length; i++){
        var item = dataList[i];
        let index = i + (page - 1) * pageSize + 1;
        item["index"] = index;
        data.push(item);
      }
    }
    //分页
    let pagination = {
      showQuickJumper: true,
      showSizeChanger: true,
      defaultCurrent: pageSize,
      total: total,
      pageSizeOptions: ['10', '20', '30', '40'],
      current: page,
      onShowSizeChange: this.onShowSizeChange.bind(this),
      onChange: this.onPageChange.bind(this),
      showTotal: (total) => ('共有' + total + '条数据')
    };
    /**
     * table配置 ********** 结束 ****************
     * */

    var addArr = [];
    if (checks(checksAdd)){
      addArr.push(
        <div key="add" className={styles.tableListOperator}>
          <Link to={addPath}><Button icon="plus">新建</Button></Link>
        </div>
      )
    }


    return (
      <PageHeaderWrapper title={title}>
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>
              {
                this.renderForm()
              }
            </div>
            {
              checks(checksAdd) ? addArr : null
            }
            <br/>
            <Table
              columns={this.state.columns}
              //rowKey={record => record.login.uuid}
              dataSource={data}
              pagination={pagination}
              loading={loading}
              scroll={{ x: this.state.scrollX }}
              // onChange={this.handleTableChange.bind(this)}
            />
          </div>
        </Card>
      </PageHeaderWrapper>
    );
  }
}
